package com.example.dome.binary;

import org.apache.commons.lang3.StringUtils;

public class Test {

    public static void main(String[] args) {
        String userName = "zhangs";
        long customerId = getCustomerId(userName);
        long orderNo = getOrder(customerId);

        System.out.println("userName:"+userName + ",shard:" +shard(userName,4));
        System.out.println("customerId:"+customerId + ",shard:" +shard(customerId,4));
        System.out.println("orderNo:"+orderNo + ",shard:" +shard(orderNo,4));


    }

    public static int shard(long id,int shard){
        if(shard>10000){
            throw new IllegalArgumentException("shard < 10000 ! ");
        }
        if(shard>id){
            return (int) id;
        }
        String s = Long.toBinaryString(id);
        String s1 = s.substring(s.length() - shard/2);
        return Integer.parseInt(s1,2);
    }

    public static int shard(String str,int shard){
        int id = Math.abs(str.hashCode());
        if(shard>10000){
            throw new IllegalArgumentException("shard < 10000 ! ");
        }
        if(shard>id){
            return id;
        }
        String s = Long.toBinaryString(id);
        String s1 = s.substring(s.length() - shard/2);
        return Integer.parseInt(s1,2);
    }

    public static long getOrder(long customerId){
        StringBuilder orderNo = new StringBuilder(String.valueOf(System.currentTimeMillis()));
        if(customerId<1000){
            orderNo.append(String.format("%04d",customerId));
            return Long.valueOf(orderNo.toString());
        }
        String s = String.valueOf(customerId);
        String s1 = s.substring(s.length() - 4);
        orderNo.append(s1);
        return Long.valueOf(orderNo.toString());
    }

    public static long getCustomerId(String username){
        StringBuilder customerId = new StringBuilder(String.valueOf(System.currentTimeMillis()));
        int hashCode = Math.abs(username.hashCode());
        if(hashCode<1000){
            customerId.append(String.format("%04d",hashCode));
            return Long.valueOf(customerId.toString());
        }
        String s = String.valueOf(hashCode);
        String s1 = s.substring(s.length() - 4);
        customerId.append(s1);
        return Long.valueOf(customerId.toString());
    }


//    public static String shard(String str){
//        return toBinary8(str.hashCode());
//    }
}
